package com.bblocks.common.anti_reptile.data.es;


import com.bblocks.common.anti_reptile.config.AntiReptileProperties;
import com.bblocks.common.anti_reptile.constant.AntiReptileConsts;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.data.elasticsearch.client.ClientConfiguration;
import org.springframework.data.elasticsearch.client.RestClients;
import org.springframework.data.elasticsearch.config.AbstractElasticsearchConfiguration;

import javax.annotation.Resource;

/**
 * <p>Project: bb-anti-reptile - ElasticConfig</p>
 * <p>描述：</p>
 *
 * @Author Zhao [125043150@qq.com]
 * @Date 2024/3/29 11:27
 * @Version 1.0
 * @since 8
 */
@ConditionalOnProperty(name = "anti.reptile.es.host", matchIfMissing = false)
public class ElasticConfig extends AbstractElasticsearchConfiguration {
    @Resource
    private AntiReptileProperties antiReptileProperties;

    @Bean(name = AntiReptileConsts.ES_CLIENT_ANTI, destroyMethod = "close")
    public RestHighLevelClient elasticsearchClient() {
        if(antiReptileProperties.getEs().getUsername() == null || antiReptileProperties.getEs().getUsername().isEmpty()){
            final ClientConfiguration clientConfiguration = ClientConfiguration.builder()
                    .connectedTo(antiReptileProperties.getEs().getHost()+":"+antiReptileProperties.getEs().getPort())
                    .withSocketTimeout(600000)
                    .build();
            return RestClients.create(clientConfiguration).rest();
        }else{
            final ClientConfiguration clientConfiguration = ClientConfiguration.builder()
                    .connectedTo(antiReptileProperties.getEs().getHost()+":"+antiReptileProperties.getEs().getPort())
                    .withBasicAuth(antiReptileProperties.getEs().getUsername(), antiReptileProperties.getEs().getPassword())
                    .withSocketTimeout(600000)
                    .build();
            return RestClients.create(clientConfiguration).rest();
        }
    }
}
